﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sys.WebRes.Data;
using Sys.WebRes.Publish.Areas.Admin.Models;
using System.IO;
using System.Drawing;

namespace Sys.WebRes.Publish.Areas.Admin.Controllers
{
    public class AttachController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">资源类型ID</param>
        /// <param name="ctype">自定义分类名</param>
        /// <returns></returns>
        public ActionResult List(int? id, string ctype, int page = 1, int rows = 20)
        {
            using (var db = new ResourceSysEntities())
            {
                string exts = (id == null) ? null : ResType.Map[id ?? ResType.File.ID].Ext;
                string type = string.IsNullOrEmpty(ctype) ? null : ctype;
                var query = db.AttachmentTBL.Where(p => (exts == null || exts.Contains(p.Extension))
                                                    && (type == null || p.CustomType == "" || p.CustomType == type));

                int count = query.Count();

                var list = query.Take(rows * page).OrderBy(p => p.CreateDate)
                                .Skip((page - 1) * rows)
                                .Select(p => new AttachmentModel{
                                    ID = p.ID,
                                    Title = p.Title,
                                    Summary = p.Summary,
                                    Folder = p.Folder,
                                    FileName = p.FileName,
                                    Extension = p.Extension,
                                    PicWidth = p.PicWidth,
                                    PicHeight = p.PicHeight,
                                    CustomType = p.CustomType,
                                    CreateDate = p.CreateDate})
                                .ToList();

                return Json(new { total = count, rows = list }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int? id)
        {
            var model = new AttachmentModel();
            if (id > 0)
            {
                using (var db = DB.New)
                {
                    var entity = db.AttachmentTBL.FirstOrDefault(p => p.ID == id);
                    entity.CopyTo(model);
                }
            }

            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="filePath">Pic/2011-11/xxxx.eee</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int? id, AttachmentModel model)//, string filePath)
        {
            if (this.Request.Files.Count > 0)
            {
                var file = this.Request.Files[0];
                if (!string.IsNullOrEmpty(file.FileName))
                {
                    var upload = UploadFile(file, model, model.FilePath, false);
                    model.Folder = upload[0];
                    model.FileName = upload[1];
                    model.Extension = upload[2];
                }
            }
            if (!string.IsNullOrEmpty(model.FileName))
            {
                using (var tran = DB.NewTran)
                {
                    using (var db = DB.New)
                    {
                        Attachment entity = null;
                        if (id == null || id == 0)
                        {
                            entity = new Attachment() { ID = (db.AttachmentTBL.Max<Attachment, int?>(p => p.ID) ?? 0) + 1 };
                            db.AddToAttachmentTBL(entity);
                            model.ID = entity.ID;
                        }
                        else
                        {
                            entity = db.AttachmentTBL.FirstOrDefault(p => p.ID == id);
                        }

                        entity.CopyFrom(model);
                        entity.CreateDate = DateTime.Now;
                        db.SaveChanges();
                    }
                    tran.Complete();
                }
            }
            this.ModelState.Clear();
            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">资源类型ID</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult BatchUpload(int id)
        {
            var uploadFolder = SysConfig.UploadFileFolder;
            if (ResType.Picture.ID == id)
            {
                uploadFolder = SysConfig.UploadPictureFolder;
            }
            else if (ResType.Media.ID == id)
            {
                uploadFolder = SysConfig.UploadMediaFolder;
            }

            ViewData["uploadFolder"] = uploadFolder;
            List<AttachmentModel> models = new List<AttachmentModel>()
            {
                new AttachmentModel(),
                new AttachmentModel(),
                new AttachmentModel(),
            };
            return View(models);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchUpload(List<AttachmentModel> models, string uploadFolder)
        {
            using (var tran = DB.NewTran)
            {
                using (var db = DB.New)
                {
                    UploadFiles(models, Request.Files, uploadFolder, db);
                    db.SaveChanges();
                }
                tran.Complete();
            }

            models.RemoveAll(p => p.ID <= 0);

            ViewData["uploadFolder"] = uploadFolder;
            this.ModelState.Clear();
            return View(models);
        }

        /// <summary>
        /// 上传文件,并保存到数据库
        /// </summary>
        /// <param name="models"></param>
        /// <param name="files"></param>
        /// <param name="uploadFolder"></param>
        /// <param name="db"></param>
        /// <param name="now"></param>
        [NonAction]
        public List<Attachment> UploadFiles(List<AttachmentModel> models, HttpFileCollectionBase files, string uploadFolder, ResourceSysEntities db)
        {
            var result = new List<Attachment>();
            var maxID = 0;
            for (int i = 0; i < files.Count; i++)
            {
                var model = models[i];
                var file = files[i];
                if (!string.IsNullOrEmpty(file.FileName) && !models[i].DeleteFlag)
                {
                    var upload = UploadFile(file, model, uploadFolder, true);
                    model.Folder = upload[0];
                    model.FileName = upload[1];
                    model.Extension = upload[2];
                }
                if (!string.IsNullOrEmpty(model.FileName) && !models[i].DeleteFlag)
                {
                    if (maxID == 0)
                    {
                        maxID = (db.AttachmentTBL.Max<Attachment, int?>(p => p.ID) ?? 0);
                    }

                    var entity = new Attachment() { ID = ++maxID };
                    entity.CopyFrom(model);
                    entity.CreateDate = db.Now;
                    db.AddToAttachmentTBL(entity);

                    result.Add(entity);
                    model.ID = entity.ID;
                }
            }
            db.SaveChanges();

            models.RemoveAll(p => p.ID <= 0 || p.DeleteFlag == true);
            var list = models.OrderBy(p => p.OrderNo).ToList();
            models.Clear();
            models.AddRange(list);

            return result;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <param name="model"></param>
        /// <returns>{"Pic/2011-11", "201111011xxx.jpg", "jpg"}</returns>
        private string[] UploadFile(HttpPostedFileBase file, AttachmentModel model, string filePath, bool onlyPath)
        {
            var fileName = "";
            var fileExt = "";
            var subFolder = "";
            if (string.IsNullOrEmpty(filePath) || onlyPath == true)
            {
                fileName = Path.GetFileName(file.FileName);
                fileExt = Path.GetExtension(fileName);
                subFolder = string.IsNullOrEmpty(filePath) ? CreateSubFolder(fileExt) : filePath;
                if(SysConfig.RenameUploadFile)
                {
                    fileName = DateTime.Now.ToString(SysConfig.UploadFileNameFormat) + fileExt;
                }
            }
            else
            {
                subFolder = Path.GetDirectoryName(filePath);
                fileName = Path.GetFileName(filePath);
                fileExt = Path.GetExtension(fileName);
            }

            var uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SysConfig.UploadFolder);
            uploadFolder = Path.Combine(uploadFolder, subFolder);

            System.IO.Directory.CreateDirectory(uploadFolder);

            fileExt = string.IsNullOrEmpty(fileExt) ? "" : fileExt.Substring(1);
            if (ResType.Picture.Ext.Contains(fileExt))
            {
                var size = SavePicture(file, uploadFolder, fileName, fileExt);
                model.PicWidth = size.Width;
                model.PicHeight = size.Height;
            }
            else if (ResType.Media.Ext.Contains(fileExt))
            {
                SaveMedia(file, uploadFolder, fileName, fileExt);
            }
            else if (ResType.File.Ext.Contains(fileExt))
            {
                SaveFile(file, uploadFolder, fileName, fileExt);
            }

            return new string[] { subFolder, fileName, fileExt };
        }

        /// <summary>
        /// 保存图片并生成缩略图
        /// </summary>
        /// <param name="file"></param>
        /// <param name="fileName"></param>
        /// <param name="fileExt"></param>
        /// <param name="uploadFolder"></param>
        private Size SavePicture(HttpPostedFileBase file, string uploadFolder, string fileName, string fileExt)
        {
            file.SaveAs(Path.Combine(uploadFolder, fileName));
            
            using (Image image = Image.FromStream(file.InputStream))
            {
                int nWidth = 0;
                int nHeight = 0;
                if (image.Width > image.Height)
                {
                    nWidth = SysConfig.ThumbWidth;
                    nHeight = image.Height * SysConfig.ThumbWidth / image.Width;
                }
                else
                {
                    nWidth = image.Width * SysConfig.ThumbWidth / image.Height;
                    nHeight = SysConfig.ThumbWidth;
                }

                using (Image sImage = new Bitmap(image, nWidth, nHeight))
                {
                    sImage.Save(Path.Combine(uploadFolder, SysConfig.ThumbPrefix + fileName));
                }

                return new Size ( image.Width, image.Height );
            }
        }

        /// <summary>
        /// 保存视频并生成缩略图
        /// </summary>
        /// <param name="file"></param>
        /// <param name="uploadFolder"></param>
        /// <param name="fileName"></param>
        /// <param name="fileExt"></param>
        private void SaveMedia(HttpPostedFileBase file, string uploadFolder, string fileName, string fileExt)
        {
            file.SaveAs(Path.Combine(uploadFolder, fileName));
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="uploadFolder"></param>
        /// <param name="fileName"></param>
        /// <param name="fileExt"></param>
        private void SaveFile(HttpPostedFileBase file, string uploadFolder, string fileName, string fileExt)
        {
            file.SaveAs(Path.Combine(uploadFolder, fileName));
        }

        /// <summary>
        /// 根据后缀获取文件保存路径（相对于上传路径的）
        /// </summary>
        /// <param name="fileExt">.jpg</param>
        /// <returns></returns>
        private string CreateSubFolder(string fileExt)
        {
            string result = null;

            var dateTimeFolder = DateTime.Now.ToString(SysConfig.UploadFolderNameFormat);

            if(!string.IsNullOrEmpty(fileExt))
            {
                fileExt = fileExt.Substring(1);
                if (ResType.Picture.Ext.Contains(fileExt))
                {
                    result = Path.Combine(SysConfig.UploadPictureFolder, dateTimeFolder);
                }
                else if (ResType.Media.Ext.Contains(fileExt))
                {
                    result = Path.Combine(SysConfig.UploadMediaFolder, dateTimeFolder);
                }
            }

            result = result ?? Path.Combine(SysConfig.UploadFileFolder, dateTimeFolder);

            return result;
        }
    }
}
